Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

assert-never

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

assert-never

Helper function for exhaustive checks of discriminated unions in TypeScript

  • 1.4.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.5M
decreased by-1.65%
Maintainers
1
Weekly downloads
 
Created

What is assert-never?

The assert-never package is a TypeScript utility that helps ensure exhaustive checks in switch statements and other control flow structures. It is particularly useful for handling TypeScript's union types and ensuring that all possible cases are handled, providing a compile-time error if a case is missed.

What are assert-never's main functionalities?

Exhaustive Check in Switch Statements

This feature ensures that all possible cases of a union type are handled in a switch statement. If a new type is added to the union and not handled in the switch, TypeScript will throw a compile-time error.

function assertNever(x: never): never {
  throw new Error("Unexpected object: " + x);
}

type Shape = 'circle' | 'square' | 'triangle';

function getArea(shape: Shape): number {
  switch (shape) {
    case 'circle':
      return Math.PI * 1 * 1; // Example area calculation
    case 'square':
      return 1 * 1; // Example area calculation
    case 'triangle':
      return 0.5 * 1 * 1; // Example area calculation
    default:
      return assertNever(shape);
  }
}

Exhaustive Check in If-Else Statements

This feature ensures that all possible cases of a union type are handled in an if-else statement. If a new type is added to the union and not handled in the if-else, TypeScript will throw a compile-time error.

function assertNever(x: never): never {
  throw new Error("Unexpected object: " + x);
}

type Color = 'red' | 'green' | 'blue';

function getColorCode(color: Color): string {
  if (color === 'red') {
    return '#FF0000';
  } else if (color === 'green') {
    return '#00FF00';
  } else if (color === 'blue') {
    return '#0000FF';
  } else {
    return assertNever(color);
  }
}

Other packages similar to assert-never

Keywords

FAQs

Package last updated on 17 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc